<template>
  <div class="history-list">
    <van-nav-bar title="我的浏览记录" left-arrow @click-left="goBack" />
    
    
    <div v-if="loading" class="loading">加载中...</div>

    <div v-else-if="historyList.length === 0" class="empty">
      暂无浏览记录
    </div>

    <ul v-else-if="historyList.length > 0">
      <li v-for="item in historyList" :key="item.id" class="history-item">
        <div class="product-info">
          <img :src="item.product.image_url || 'https://picsum.photos/100/100'" :alt="item.product.name"
            class="product-img" @error="handleImageError($event, item)">
          <div class="details">
            <h3>{{ item.product.name || '未知商品' }}</h3>
            <p class="price">
              ￥{{ formatPrice(item.product.price) }}
            </p>
            <p class="time">浏览时间：{{ formatTime(item.redis_browse_timestamp) }}</p>
          </div>
        </div>
      </li>
    </ul>

    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>
  </div>
  <Button></Button>
</template>

<script setup>
import { onMounted, ref, reactive, toRefs } from 'vue';
import { useRoute, useRouter} from 'vue-router';
import Button from '@/components/Button.vue';
import { getBrowseHistory } from '@/api/history';
const router = useRouter();
const route = useRoute()
const state = reactive({
  userId: route.params.userId || 1,
  historyList: [],
  loading: true,
  errorMessage: '',
});

const { userId, historyList, loading, errorMessage } = toRefs(state);

// 返回上一页
const goBack = () => {
  router.back();
};

// 格式化价格
const formatPrice = (price) => {
  try {
    if (price === undefined || price === null) return '0.00';
    const numericPrice = Number(price);
    return isNaN(numericPrice) ? '0.00' : numericPrice.toFixed(2);
  } catch (error) {
    console.error('价格格式化错误:', error);
    return '0.00';
  }
};

const formatTime = (timestamp) => {
  try {
    if (!timestamp) return '未知时间';
    const date = new Date(timestamp * 1000);
    if (isNaN(date.getTime())) {
      return '格式错误';
    }
    return date.toLocaleString();
  } catch (error) {
    console.error('时间格式化错误:', error);
    return '格式错误';
  }
};

const handleImageError = (event, item) => {
  console.warn('图片加载失败:', event.target.src);
  item.product.image_url = 'https://picsum.photos/100/100';
};

onMounted(async () => {
  try {
    loading.value = true;
    errorMessage.value = '';

    const data = await getBrowseHistory(userId.value);
    console.log('原始数据:', data);

    if (!Array.isArray(data)) {
      throw new Error('获取的数据格式不正确');
    }

    historyList.value = data.map(item => {
      if (!item || !item.product) {
        console.warn('无效的历史记录项:', item);
        return null;
      }
      const safeProduct = {
        id: item.product.id || 0,
        name: item.product.name || '未知商品',
        price: item.product.price !== undefined ? item.product.price : 0,
        image_url: item.product.image_url || 'https://picsum.photos/100/100',
      };

      return {
        ...item,
        product: safeProduct,
        browse_time: item.browse_time || new Date().toISOString(),
      };
    }).filter(Boolean);

    console.log('处理后的数据:', historyList.value);

    if (historyList.value.length === 0) {
      console.info('浏览记录为空');
    }
  } catch (error) {
    console.error('获取浏览记录失败:', error);
    errorMessage.value = '获取浏览记录失败，请稍后再试';
  } finally {
    loading.value = false;
  }
});
</script>

<style scoped>
.history-list {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.loading,
.empty {
  text-align: center;
  padding: 50px;
  color: #666;
  font-size: 1.2em;
}

.error-message {
  text-align: center;
  padding: 20px;
  color: #f00;
  background-color: #ffebee;
  border-radius: 4px;
  margin-top: 15px;
}

.history-item {
  list-style: none;
  padding: 15px;
  border-bottom: 1px solid #eee;
  display: flex;
  gap: 15px;
  transition: background-color 0.2s;
}

.history-item:hover {
  background-color: #f8f9fa;
}

.product-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.price {
  color: #f00;
  font-weight: bold;
  margin: 5px 0;
  font-size: 1.1em;
}

.time {
  color: #999;
  font-size: 0.9em;
}
</style>